//
//  PLISTSaveManager.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/8/17.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class Plist_historyMode:HandyJSON {
    var roomId:String!
    var name:String!
    
    init(roomId:String,name:String) {
        self.roomId = roomId
        self.name = name
    }
    
    required init() {}
}

class PLISTSaveManager: PLISTManage {
    
    static let meetings_hostiry_key = "meetings_hostiry_key"
    static let meetings_hostiry_plist = "meetings_hostiry.plist"
    
    
    class func restList() -> () {
        PLISTSaveManager.saveData(key: self.meetings_hostiry_key, value: [], fileName: self.meetings_hostiry_plist)
    }
    
    class func readList() -> [String]{
        let list = PLISTSaveManager.researchData(key: self.meetings_hostiry_key, fileName: self.meetings_hostiry_plist) as! [String]
        return list
    }
    
    class func appendAndSaveString(_ value:String) {
        var plist = PLISTSaveManager.researchData(key: self.meetings_hostiry_key, fileName: self.meetings_hostiry_plist) as! [String]
        let encode = value.removingPercentEncoding ?? value
        if plist.contains(encode) {
            plist.remove(objct: encode)
            plist.insert(encode, at: 0)
        }else {
            plist.insert(encode, at: 0)
        }
        plist.removeDuplicates()
        PLISTSaveManager.saveData(key: self.meetings_hostiry_key, value: plist, fileName: self.meetings_hostiry_plist)
    }
    
    class func appendAndSave(mode:Plist_historyMode)  {
        let plist = PLISTSaveManager.researchData(key: self.meetings_hostiry_key, fileName: self.meetings_hostiry_plist) as! [String]
        var modeList:[Plist_historyMode] = []
        for (_,value) in plist.enumerated() {
            if let lmode = Plist_historyMode.deserialize(from: value.toDict()) {
               modeList.append(lmode)
            }
        }
        
        let firstIndex = modeList.firstIndex { (lmode) -> Bool in
            return lmode.roomId == mode.roomId
        }
        if firstIndex != nil {
            modeList.remove(at: firstIndex!)
            modeList.insert(mode, at: 0)
        }else {
            modeList.insert(mode, at: 0)
        }
        let modeDups = modeList.hremovingDuplicates()
        
        var newList:[String] = []
        modeDups.forEach { (info) in
            if let string = info.toJSONString() {
               newList.append(string)
            }
        }
        PLISTSaveManager.saveData(key: self.meetings_hostiry_key, value: newList, fileName: self.meetings_hostiry_plist)
        
    }
    
    class func getDataString(mode:Plist_historyMode) -> String? {
        let md = Plist_historyMode.init(roomId: mode.roomId, name: mode.name)
        return md.toJSON()?.toJsonString()
    }
    
    
}
